﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// UrlRewriter URL重写类
/// edit by skybot
///  from blog:http://yangmingsheng.cn
/// </summary>
public class UrlRewriter : IHttpHandler, System.Web.SessionState.IRequiresSessionState    //这个东东用于访问 session 状态
{


    public UrlRewriter()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    String Rh;
    public void ProcessRequest(HttpContext Context)
    {
        //取得原始URL屏蔽掉参数
        string Url = Context.Request.RawUrl;
        
        System.Xml.XmlDocument Dom = new System.Xml.XmlDocument();
        Dom.Load(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["urlRewriter"]));//从web.config读取设置文件URLRewriterSettings.xml的路径
        System.Xml.XmlNodeList ItemList = Dom.SelectSingleNode(@"//URLRewriters").ChildNodes;
        foreach (System.Xml.XmlNode Node in ItemList)
        {
            //if(!Node.HasChildNodes) continue;
            String Ph = Node.Attributes.GetNamedItem(@"Path").InnerText;
             Rh = Node.Attributes.GetNamedItem(@"RealPath").InnerText;
            if (Ph.StartsWith(@"~")) Ph = HttpContext.Current.Request.ApplicationPath + Ph.Substring(1);
            if (Rh.StartsWith(@"~")) Rh = HttpContext.Current.Request.ApplicationPath + Rh.Substring(1);
            //建立正则表达式
            System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex(Ph, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Match m = Reg.Match(Url);//匹配
            if (m.Success)//成功
            {
                for (int i = 1; i <= m.Groups.Count; i++)
                {
                    Rh = Rh.Replace("$" + i.ToString(), m.Groups[i].Value);
                }
                
                //Context.Response.Write(Context.Request.Url.PathAndQuery);
                //Context.RewritePath(RealPath);//(RewritePath 用在无 Cookie 会话状态中。)

                Context.Server.Execute(Rh);
                Context.Response.End();
                break;
            }

        }
        try
        {
            Context.Server.Execute(Context.Request.Url.PathAndQuery);
        }
        catch(Exception ex)
        {
            Context.Response.Write("404 ERROR！<br/>" + ex.Message);
            Context.Response.Write(Rh);
            Context.Response.End();
        }
    }
    /// <summary>
    /// 实现“IHttpHandler”接口所必须的成员
    /// </summary>
    /// <value></value>
    /// Author:yoyo
    /// blog:http://yangmingsheng.cn
    public bool IsReusable
    {
        get { return false; }
    }

}
